<template>
  <div class="dashboard-container">
    <!-- 顶部导航栏 -->
    <div class="top-navbar">
      <div class="navbar-left">
        <div class="logo">Draw-Evo</div>
      </div>
<!--      <div class="navbar-center">-->
<!--        <nav class="nav-links">-->
<!--          <a href="#" class="nav-link active">首页</a>-->
<!--          <a href="#" class="nav-link">模板</a>-->
<!--          <a href="#" class="nav-link">创作指南</a>-->
<!--          <a href="#" class="nav-link">社区</a>-->
<!--        </nav>-->
<!--      </div>-->
      <div class="navbar-right">
        <el-icon class="nav-icon"><Bell /></el-icon>
        <UserDropdown />
      </div>
    </div>

    <!-- 主内容区域 -->
    <div class="main-content" :class="{ 'blur-content': !isLoggedIn }">
      <!-- 页面标题和搜索区域 -->
      <div class="page-header">
        <div class="page-title">
          <h1>首页 / Dashboard</h1>
          <p class="welcome-text">欢迎回来</p>
        </div>
        <div class="search-section">
          <div class="search-box">
            <el-input
              v-model="searchQuery"
              placeholder="搜索我的小说"
              class="search-input"
              @keyup.enter="handleSearch"
              clearable
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
          </div>
          <el-button type="primary" class="new-novel-btn" @click="handleCreateNovel">
            <el-icon><Plus /></el-icon>
            新建小说
          </el-button>
        </div>
      </div>

      <!-- 信息卡片区域 -->
<!--      <div class="info-cards">-->
<!--        &lt;!&ndash; 最近编辑卡片 &ndash;&gt;-->
<!--        <div class="info-card recent-edits">-->
<!--          <div class="card-header">-->
<!--            <h3>最近编辑</h3>-->
<!--            <p>继续您未完成的作品</p>-->
<!--          </div>-->
<!--          <div class="card-content">-->
<!--            <div class="novel-item" v-for="item in recentEdits" :key="item.id">-->
<!--              <div class="novel-info">-->
<!--                <h4>{{ item.title }}</h4>-->
<!--                <p class="edit-time">上次编辑: {{ item.lastEdit }}</p>-->
<!--              </div>-->
<!--            </div>-->
<!--          </div>-->
<!--        </div>-->

<!--        &lt;!&ndash; 模板推荐卡片 &ndash;&gt;-->
<!--        <div class="info-card template-recommendations">-->
<!--          <div class="card-header">-->
<!--            <h3>模板推荐</h3>-->
<!--            <p>从专业模板开始创作</p>-->
<!--          </div>-->
<!--          <div class="card-content">-->
<!--            <div class="template-item" v-for="item in templateRecommendations" :key="item.id">-->
<!--              <div class="template-info">-->
<!--                <h4>{{ item.title }}</h4>-->
<!--                <p class="usage-count">已使用 {{ item.usageCount }} 次</p>-->
<!--              </div>-->
<!--            </div>-->
<!--          </div>-->
<!--        </div>-->
<!--      </div>-->

      <!-- 我的小说区域 -->
      <div class="my-novels-section">
        <div class="section-header">
          <h2>我的小说</h2>
          <div class="sort-options">
            <span>排序: 最近编辑</span>
            <el-icon class="dropdown-icon"><ArrowDown /></el-icon>
          </div>
        </div>

        <!-- 小说网格 -->
        <div class="novels-grid" v-loading="loading">
          <div class="novel-card" v-for="novel in novels" :key="novel.id" @click="handleNovelClick(novel)">
            <div class="novel-image">
              <img :src="getImageUrl(novel.img) || getDefaultImage()" :alt="novel.name" />
            </div>
            <div class="novel-details">
              <h3 class="novel-title">{{ novel.name }}</h3>
              <p class="novel-genre">{{ novel.type || '未分类' }}</p>
              <p class="novel-update">更新于 {{ formatDate(novel.updateTime) }}</p>
              <div class="novel-status">
                <el-tag type="primary">
                  {{ novel.name ? '已创建' : '草稿' }}
                </el-tag>
              </div>
            </div>
            <div class="novel-actions" @click.stop>
              <el-dropdown @command="(command) => handleNovelAction(command, novel)" trigger="click">
                <el-icon class="more-icon"><MoreFilled /></el-icon>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item command="edit">
                      <el-icon><Edit /></el-icon>
                      编辑
                    </el-dropdown-item>
                    <el-dropdown-item command="delete" class="danger-item">
                      <el-icon><Delete /></el-icon>
                      删除
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>
          </div>

          <!-- 空状态 -->
          <div v-if="!loading && novels.length === 0" class="empty-state">
            <div class="empty-content">
              <el-icon class="empty-icon"><Document /></el-icon>
              <p class="empty-text">暂无小说，点击"新建小说"开始创作吧！</p>
            </div>
          </div>
        </div>

        <!-- 分页 -->
        <div class="pagination-container" v-if="totalNovels > 0">
          <el-pagination
            v-model:current-page="currentPage"
            :page-size="pageSize"
            :total="totalNovels"
            layout="prev, pager, next"
            class="pagination"
            @current-change="handlePageChange"
          />
        </div>
      </div>
    </div>

<!--    &lt;!&ndash; 页脚 &ndash;&gt;-->
<!--    <div class="footer">-->
<!--      <div class="footer-content">-->
<!--        <div class="footer-left">-->
<!--          <div class="footer-logo">小说创作平台</div>-->
<!--          <p class="footer-description">-->
<!--            专业的在线小说创作平台, 助力每一位创作者实现文学梦想。-->
<!--          </p>-->
<!--          <p class="footer-copyright">-->
<!--            © 2023 小说创作平台, 保留所有权利。-->
<!--          </p>-->
<!--        </div>-->
<!--        <div class="footer-middle">-->
<!--          <div class="footer-section">-->
<!--            <h4>产品</h4>-->
<!--            <ul>-->
<!--              <li><a href="#">创作工具</a></li>-->
<!--              <li><a href="#">模板库</a></li>-->
<!--              <li><a href="#">数据分析</a></li>-->
<!--              <li><a href="#">出版服务</a></li>-->
<!--            </ul>-->
<!--          </div>-->
<!--          <div class="footer-section">-->
<!--            <h4>资源</h4>-->
<!--            <ul>-->
<!--              <li><a href="#">帮助中心</a></li>-->
<!--              <li><a href="#">创作指南</a></li>-->
<!--              <li><a href="#">作者社区</a></li>-->
<!--              <li><a href="#">API文档</a></li>-->
<!--            </ul>-->
<!--          </div>-->
<!--        </div>-->
<!--        <div class="footer-right">-->
<!--          <div class="footer-section">-->
<!--            <h4>联系我们</h4>-->
<!--            <p>support@novelcreator.com</p>-->
<!--            <p>400-123-4567</p>-->
<!--            <p>北京市朝阳区创意产业园A座</p>-->
<!--          </div>-->
<!--          <div class="social-icons">-->
<!--            <el-icon class="social-icon"><Share /></el-icon>-->
<!--            <el-icon class="social-icon"><ChatDotRound /></el-icon>-->
<!--            <el-icon class="social-icon"><Star /></el-icon>-->
<!--          </div>-->
<!--        </div>-->
<!--      </div>-->
<!--    </div>-->

    <!-- 登录弹窗 -->
    <el-dialog
      v-model="showLoginDialog"
      title="请登录"
      width="400px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :show-close="false"
      center
      class="login-dialog-overlay"
    >
      <LoginDialog @login-success="handleLoginSuccess" @show-register="handleShowRegister" />
    </el-dialog>

    <!-- 注册弹窗 -->
    <el-dialog
      v-model="showRegisterDialog"
      title="用户注册"
      width="400px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :show-close="false"
      center
      class="register-dialog-overlay"
    >
      <RegisterDialog @register-success="handleRegisterSuccess" @show-login="handleShowLogin" />
    </el-dialog>

    <!-- 新建小说弹窗 -->
    <CreateNovelDialog
      v-model="showCreateNovelDialog"
      @success="handleCreateNovelSuccess"
    />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed, watch } from 'vue'
import { useRouter } from 'vue-router'
import useUserStore from '@/store/modules/user'
import LoginDialog from './components/LoginDialog.vue'
import RegisterDialog from './components/RegisterDialog.vue'
import UserDropdown from './components/UserDropdown.vue'
import CreateNovelDialog from './components/CreateNovelDialog.vue'
import { listNovel, delNovel } from '@/api/novel/novel'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Bell,
  Search,
  Plus,
  MoreFilled,
  Share,
  ChatDotRound,
  Star,
  Document,
  Edit,
  Delete
} from '@element-plus/icons-vue'

// 用户store
const userStore = useUserStore()
const router = useRouter()

// 响应式数据
const searchQuery = ref('')
const currentPage = ref(1)
const pageSize = ref(6)
const totalNovels = ref(0)
const loading = ref(false)

// 登录状态
const isLoggedIn = computed(() => !!userStore.token)
const showLoginDialog = ref(false)
const showRegisterDialog = ref(false)
const showCreateNovelDialog = ref(false)

// 最近编辑数据
const recentEdits = reactive([
  {
    id: 1,
    title: '星辰大海的征途',
    lastEdit: '2小时前'
  },
  {
    id: 2,
    title: '都市异闻录',
    lastEdit: '昨天'
  }
])

// 模板推荐数据
const templateRecommendations = reactive([
  {
    id: 1,
    title: '悬疑小说模板',
    usageCount: '1.2k'
  },
  {
    id: 2,
    title: '青春文学模板',
    usageCount: '856'
  }
])

// 小说数据
const novels = ref([])

// 登录成功处理
const handleLoginSuccess = () => {
  showLoginDialog.value = false
  // 登录成功后加载小说数据
  loadNovels()
}

// 显示注册弹窗
const handleShowRegister = () => {
  showLoginDialog.value = false
  showRegisterDialog.value = true
}

// 注册成功处理
const handleRegisterSuccess = () => {
  showRegisterDialog.value = false
  showLoginDialog.value = true
}

// 显示登录弹窗
const handleShowLogin = () => {
  showRegisterDialog.value = false
  showLoginDialog.value = true
}

// 显示新建小说弹窗
const handleCreateNovel = () => {
  if (!isLoggedIn.value) {
    showLoginDialog.value = true
    return
  }
  showCreateNovelDialog.value = true
}


// 新建小说成功处理
const handleCreateNovelSuccess = (novelData) => {
  showCreateNovelDialog.value = false
  // 刷新小说列表
  loadNovels()
  ElMessage.success('小说创建成功')
}

// 加载小说列表
const loadNovels = async () => {
  if (!isLoggedIn.value) return

  try {
    loading.value = true
    const params = {
      pageNum: currentPage.value,
      pageSize: pageSize.value
    }

    // 如果有搜索关键词，添加到参数中
    if (searchQuery.value.trim()) {
      params.name = searchQuery.value.trim()
    }

    const response = await listNovel(params)

    if (response.code === 200) {
      novels.value = response.rows || []
      totalNovels.value = response.total || 0
    } else {
      ElMessage.error(response.msg || '获取小说列表失败')
    }
  } catch (error) {
    console.error('Load novels error:', error)
    ElMessage.error('获取小说列表失败，请重试')
  } finally {
    loading.value = false
  }
}

// 搜索小说
const handleSearch = () => {
  currentPage.value = 1
  loadNovels()
}

// 分页变化处理
const handlePageChange = (page) => {
  currentPage.value = page
  loadNovels()
}

// 小说卡片点击处理
const handleNovelClick = (novel) => {
  if (novel && novel.id) {
    router.push(`/novel-detail/${novel.id}`)
  }
}

// 小说操作菜单处理
const handleNovelAction = async (command, novel) => {
  if (command === 'edit') {
    // 编辑功能 - 跳转到小说详情页面
    if (novel && novel.id) {
      router.push(`/novel-detail/${novel.id}`)
    }
  } else if (command === 'delete') {
    // 删除功能
    await handleDeleteNovel(novel)
  }
}

// 删除小说
const handleDeleteNovel = async (novel) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除小说《${novel.name}》吗？删除后无法恢复！`,
      '删除确认',
      {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'warning',
        confirmButtonClass: 'el-button--danger'
      }
    )

    // 执行删除
    const response = await delNovel(novel.id)
    if (response.code === 200) {
      ElMessage.success('删除成功')
      // 刷新小说列表
      loadNovels()
    } else {
      ElMessage.error(response.msg || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('Delete novel error:', error)
      ElMessage.error('删除失败，请重试')
    }
  }
}

// 获取图片URL，添加API前缀
const getImageUrl = (imgUrl) => {
  if (!imgUrl) return null

  // 如果已经是完整URL（包含http或https），直接返回
  if (imgUrl.startsWith('http://') || imgUrl.startsWith('https://') || imgUrl.startsWith('data:')) {
    return imgUrl
  }

  // 如果是相对路径，添加API前缀
  const baseUrl = import.meta.env.VITE_APP_BASE_API || '/dev-api'
  return baseUrl + (imgUrl.startsWith('/') ? imgUrl : '/' + imgUrl)
}

// 获取默认图片
const getDefaultImage = () => {
  return ''
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return '未知'
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit'
  })
}

// 页面加载时检查登录状态
onMounted(() => {
  // 注册触发登录弹窗的函数到全局
  if (typeof window !== 'undefined') {
    import('@/utils/request').then(module => {
      module.triggerLoginDialog = () => {
        showLoginDialog.value = true
      }
    })
  }

  if (!isLoggedIn.value) {
    showLoginDialog.value = true
  } else {
    // 如果已登录，加载小说数据
    loadNovels()
  }
})

// 监听登录状态变化
watch(isLoggedIn, (newVal) => {
  if (!newVal) {
    // 当登录状态变为false时，显示登录弹窗
    showLoginDialog.value = true
  }
})
</script>

<style lang="scss" scoped>
.dashboard-container {
  min-height: 100vh;
  background-color: #f8f9fa;
}

// 主内容区域模糊效果
.main-content {
  transition: filter 0.3s ease;

  &.blur-content {
    filter: blur(5px);
    pointer-events: none;
  }
}

// 登录弹窗样式，确保不受模糊效果影响
:deep(.login-dialog-overlay) {
  pointer-events: auto !important;

  .el-dialog {
    pointer-events: auto !important;
  }

  .el-dialog__body {
    pointer-events: auto !important;
  }

  .el-form {
    pointer-events: auto !important;
  }

  .el-input {
    pointer-events: auto !important;
  }

  .el-button {
    pointer-events: auto !important;
  }
}

// 注册弹窗样式，确保不受模糊效果影响
:deep(.register-dialog-overlay) {
  pointer-events: auto !important;

  .el-dialog {
    pointer-events: auto !important;
  }

  .el-dialog__body {
    pointer-events: auto !important;
  }

  .el-form {
    pointer-events: auto !important;
  }

  .el-input {
    pointer-events: auto !important;
  }

  .el-button {
    pointer-events: auto !important;
  }
}

// 新建小说弹窗样式，确保不受模糊效果影响
:deep(.create-novel-dialog-overlay) {
  pointer-events: auto !important;

  .el-dialog {
    pointer-events: auto !important;
    max-height: 90vh;
    overflow-y: auto;
  }

  .el-dialog__body {
    pointer-events: auto !important;
    padding: 0;
  }

  .el-form {
    pointer-events: auto !important;
  }

  .el-input {
    pointer-events: auto !important;
  }

  .el-button {
    pointer-events: auto !important;
  }

  .el-select {
    pointer-events: auto !important;
  }

  .el-tag {
    pointer-events: auto !important;
  }
}

// 顶部导航栏
.top-navbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 24px;
  height: 64px;
  background: white;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  position: sticky;
  top: 0;
  z-index: 1000;

  .navbar-left {
    .logo {
      font-size: 24px;
      font-weight: bold;
      color: #409eff;
    }
  }

  .navbar-center {
    .nav-links {
      display: flex;
      gap: 32px;

      .nav-link {
        text-decoration: none;
        color: #666;
        font-weight: 500;
        transition: color 0.3s;

        &.active {
          color: #409eff;
        }

        &:hover {
          color: #409eff;
        }
      }
    }
  }

  .navbar-right {
    display: flex;
    align-items: center;
    gap: 16px;

    .nav-icon {
      font-size: 20px;
      color: #666;
      cursor: pointer;
    }

  }
}

// 主内容区域
.main-content {
  padding: 24px;
  max-width: 1200px;
  margin: 0 auto;
}

// 页面头部
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 32px;

  .page-title {
    h1 {
      font-size: 28px;
      font-weight: bold;
      color: #333;
      margin: 0 0 8px 0;
    }

    .welcome-text {
      color: #666;
      font-size: 16px;
      margin: 0;
    }
  }

  .search-section {
    display: flex;
    align-items: center;
    gap: 16px;

    .search-box {
      width: 300px;

      .search-input {
        .el-input__wrapper {
          border-radius: 8px;
        }
      }
    }

    .new-novel-btn {
      border-radius: 8px;
      padding: 12px 24px;
      font-weight: 500;
    }
  }
}

// 信息卡片区域
.info-cards {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 24px;
  margin-bottom: 32px;

  .info-card {
    padding: 24px;
    border-radius: 12px;
    color: white;

    &.recent-edits {
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    }

    &.template-recommendations {
      background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
    }

    .card-header {
      margin-bottom: 20px;

      h3 {
        font-size: 20px;
        font-weight: bold;
        margin: 0 0 8px 0;
      }

      p {
        font-size: 14px;
        opacity: 0.9;
        margin: 0;
      }
    }

    .card-content {
      .novel-item,
      .template-item {
        background: rgba(255, 255, 255, 0.1);
        padding: 16px;
        border-radius: 8px;
        margin-bottom: 12px;

        &:last-child {
          margin-bottom: 0;
        }

        h4 {
          font-size: 16px;
          font-weight: 600;
          margin: 0 0 8px 0;
        }

        p {
          font-size: 14px;
          opacity: 0.8;
          margin: 0;
        }
      }
    }
  }
}

// 我的小说区域
.my-novels-section {
  .section-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24px;

    h2 {
      font-size: 24px;
      font-weight: bold;
      color: #333;
      margin: 0;
    }

    .sort-options {
      display: flex;
      align-items: center;
      gap: 8px;
      color: #666;
      cursor: pointer;

      .dropdown-icon {
        font-size: 12px;
      }
    }
  }

  .novels-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
    gap: 24px;
    margin-bottom: 32px;

    .novel-card {
      background: white;
      border-radius: 12px;
      overflow: hidden;
      box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
      transition: transform 0.3s, box-shadow 0.3s;
      position: relative;
      cursor: pointer;

      &:hover {
        transform: translateY(-4px);
        box-shadow: 0 8px 24px rgba(0, 0, 0, 0.15);
      }

      &:active {
        transform: translateY(-2px);
      }

      .novel-image {
        height: 200px;
        overflow: hidden;
        background: linear-gradient(45deg, #ff9a9e 0%, #fecfef 100%);

        img {
          width: 100%;
          height: 100%;
          object-fit: cover;
        }
      }

      .novel-details {
        padding: 20px;

        .novel-title {
          font-size: 18px;
          font-weight: bold;
          color: #333;
          margin: 0 0 8px 0;
        }

        .novel-genre {
          color: #666;
          font-size: 14px;
          margin: 0 0 8px 0;
        }

        .novel-update {
          color: #999;
          font-size: 12px;
          margin: 0 0 12px 0;
        }

        .novel-status {
          .el-tag {
            border-radius: 4px;
          }
        }
      }

      .novel-actions {
        position: absolute;
        top: 16px;
        right: 16px;

        .more-icon {
          font-size: 20px;
          color: #666;
          cursor: pointer;
          padding: 8px;
          border-radius: 50%;
          background: rgba(255, 255, 255, 0.8);

          &:hover {
            background: rgba(255, 255, 255, 1);
          }
        }
      }
    }
  }

  // 下拉菜单样式
  :deep(.el-dropdown-menu) {
    .danger-item {
      color: #f56c6c;

      &:hover {
        background-color: #fef0f0;
        color: #f56c6c;
      }
    }
  }

  .pagination-container {
    display: flex;
    justify-content: center;

    .pagination {
      .el-pagination__item.is-active {
        background-color: #409eff;
        border-color: #409eff;
      }
    }
  }

  // 空状态样式
  .empty-state {
    grid-column: 1 / -1;
    display: flex;
    justify-content: center;
    align-items: center;
    min-height: 300px;

    .empty-content {
      text-align: center;
      color: #999;

      .empty-icon {
        font-size: 64px;
        margin-bottom: 16px;
        color: #ddd;
      }

      .empty-text {
        font-size: 16px;
        margin: 0;
      }
    }
  }
}

// 页脚
.footer {
  background: #2c3e50;
  color: white;
  padding: 48px 0 24px;
  margin-top: 64px;

  .footer-content {
    max-width: 1200px;
    margin: 0 auto;
    padding: 0 24px;
    display: grid;
    grid-template-columns: 2fr 1fr 1fr 1fr;
    gap: 48px;

    .footer-left {
      .footer-logo {
        font-size: 24px;
        font-weight: bold;
        color: #409eff;
        margin-bottom: 16px;
      }

      .footer-description {
        color: #bdc3c7;
        line-height: 1.6;
        margin-bottom: 16px;
      }

      .footer-copyright {
        color: #95a5a6;
        font-size: 14px;
        margin: 0;
      }
    }

    .footer-section {
      h4 {
        font-size: 16px;
        font-weight: bold;
        margin: 0 0 16px 0;
      }

      ul {
        list-style: none;
        padding: 0;
        margin: 0;

        li {
          margin-bottom: 8px;

          a {
            color: #bdc3c7;
            text-decoration: none;
            transition: color 0.3s;

            &:hover {
              color: #409eff;
            }
          }
        }
      }

      p {
        color: #bdc3c7;
        margin: 0 0 8px 0;
        font-size: 14px;
      }
    }

    .social-icons {
      display: flex;
      gap: 12px;
      margin-top: 16px;

      .social-icon {
        font-size: 20px;
        color: #bdc3c7;
        cursor: pointer;
        transition: color 0.3s;

        &:hover {
          color: #409eff;
        }
      }
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .top-navbar {
    padding: 0 16px;

    .navbar-center {
      display: none;
    }
  }

  .main-content {
    padding: 16px;
  }

  .page-header {
    flex-direction: column;
    gap: 16px;

    .search-section {
      width: 100%;
      flex-direction: column;

      .search-box {
        width: 100%;
      }
    }
  }

  .info-cards {
    grid-template-columns: 1fr;
  }

  .novels-grid {
    grid-template-columns: 1fr;
  }

  .footer-content {
    grid-template-columns: 1fr;
    gap: 24px;
  }
}
</style>
